from django.conf.urls.defaults import *
from django.conf import settings
from models import MenuItem, Content
from django.core.urlresolvers import get_callable
from django.http import Http404, HttpResponseRedirect

def contentpage(request):
#    url = request.path.endswith('/') and request.path or request.path + '/'
    #print request.path
    try:
        menu_item = MenuItem.objects.filter(named_url='', url=request.path)[0]
    except IndexError:
        if not request.path.endswith('/'):
            return HttpResponseRedirect(request.path + '/')
        raise Http404, 'Contentpage `%s` not found' % request.path

    # fix blank Content
    if not Content.objects.filter(menu_item=menu_item).count():
        Content(menu_item=menu_item).save()

    return get_callable(settings.CONTENTTREE_DEFAULT_VIEW)(request)

urlpatterns = patterns('', (r'^.*$', contentpage))
